const fastq = require('fastq');
const logger = require('../utils').getLogger(__filename);

module.exports = class TimesQueue {
	constructor(worker, options, concurrency) {
		this.options = options;
		this.logger = logger;
		this.times = 0;

		function runner(args, cb) {
			this.times++;
			if (this.times >= concurrency) {
				this.logger.info(`可同时执行工作量超过设定值：${concurrency}`);
				this.timeout = setTimeout(this._resume.bind(this), 1000);
				this.queue.pause();
			}
			worker.call(this, args, cb);
		}

		this.queue = fastq(runner.bind(this), 100);
		this.interval = setInterval(this._timesControl.bind(this), 1000 / concurrency);
	}

	_resume() {
		this.queue.resume();
	}

	_timesControl() {
		if (this.times > 0) {
			this.times--;
		}
	}

	push(args, done) {
		return this.queue.push(args, done);
	}
};



